<template>
  <div class="container">
    <div class="left-container">
      <div class="left-top">
        <!-- WebSocket连接配置区 -->
        <div class="row">
          <input 
            v-model="serverHost" 
            type="text" 
            placeholder="服务器IP（如：127.0.0.1）" 
            class="input-small"
            :disabled="isMeasuring"
          >
          <input 
            v-model="serverPort" 
            type="number" 
            placeholder="端口号（如：8080）" 
            class="input-tiny"
            :disabled="isMeasuring"
          >
          <span :class="['status-indicator', isConnected ? 'connected' : 'disconnected']"></span>
          <span v-if="wsError" class="error-msg">{{ wsError }}</span>
        </div>

        <div class="row">
          <input 
            v-model="lotNumber" 
            type="text" 
            placeholder="请输入批次号" 
            class="input-small"
            :disabled="isMeasuring"
          >
          <input 
            v-model="smallLotNumber" 
            type="text" 
            placeholder="小lot数" 
            class="input-tiny"
            :disabled="isMeasuring"
          >
          <button 
            @click="startMeasurement" 
            class="btn"
            :disabled="isMeasuring || !serverHost || !serverPort"
          >开始测量</button>
        </div>

        <div class="row">
          <select 
            v-model="hasCPK" 
            class="select"
            :disabled="!isMeasuring"
          >
            <option value="">是否有CPK</option>
            <option value="是">是</option>
            <option value="否">否</option>
          </select>
          <select 
            v-model="testMethod" 
            class="select"
            :disabled="!isMeasuring"
          >
            <option value="X射线">X射线</option>
            <option value="金相法">金相法</option>
          </select>
          <select 
            v-model="inspector" 
            class="select"
            :disabled="!isMeasuring"
          >
            <option v-for="person in inspectors" :key="person">{{ person }}</option>
          </select>
        </div>

        <div class="row">
          <input 
            v-model="currentData" 
            type="text" 
            placeholder="当前测量数据" 
            readonly
            class="input-disabled"
            :disabled="!isMeasuring"
          >
        </div>

        <div class="row">
          <button 
            @click="saveData" 
            class="btn"
            :disabled="!isMeasuring || !currentData"
          >保存数据</button>
          <button 
            @click="clearData" 
            class="btn"
            :disabled="!isMeasuring"
          >清空数据</button>
          <button 
            @click="deleteSelected" 
            class="btn"
            :disabled="!isMeasuring || selectedIndex === -1"
          >删除选择数据</button>
          <button 
            @click="closeConnection" 
            class="btn"
            :disabled="!isConnected"
          >断开连接</button>
        </div>
      </div>

      <div class="chart-container" ref="chartContainer"></div>
    </div>

    <div class="right-container">
      <div class="table-wrapper">
        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>批次号</th>
              <th>小lot数</th>
              <th>检测方法</th>
              <th>检测员</th>
              <th>测量值</th>
              <th>时间</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(item, index) in dataList" 
              :key="index" 
              :class="{ active: selectedIndex === index }"
              @click="selectedIndex = index"
            >
              <td>{{ index + 1 }}</td>
              <td>{{ item.lotNumber }}</td>
              <td>{{ item.smallLotNumber }}</td>
              <td>{{ item.testMethod }}</td>
              <td>{{ item.inspector }}</td>
              <td>{{ item.value }}</td>
              <td>{{ item.time }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      isMeasuring: false,    // 测量状态
      isConnected: false,    // WebSocket连接状态
      webSocket: null,       // WebSocket实例
      wsError: '',           // WebSocket错误信息
      serverHost: '127.0.0.1',  // 默认服务器IP
      serverPort: 8080,        // 默认WebSocket端口
      lotNumber: '',
      smallLotNumber: '',
      hasCPK: '',
      testMethod: 'X射线',
      inspector: '马惠玲',
      currentData: '',       // 当前测量数据
      dataList: [],          // 表格数据
      selectedIndex: -1,     // 选中行索引
      inspectors: ['马惠玲', '肖士营', '贺青青', '赵小松', '霍娟', '潘秀杰', '覃燕芳', '余贺燕', '朱雅娟', '杜江艳', '许利艳', '秦琳', '王亚楠',"于淼","xx"],
      chartInstance: null,   // ECharts实例
      chartData: {           // 图表数据
        xAxis: [],
        series: [
          { name: '测量值1', data: [] },
          { name: '测量值2', data: [] },
          { name: '测量值3', data: [] }
        ]
      }
    };
  },
  mounted() {
    this.initChart();
    this.inspector = this.inspectors[0];
  },
  beforeUnmount() {
    this.closeConnection();  // 组件卸载时关闭连接
    if (this.chartInstance) this.chartInstance.dispose();
  },
  methods: {
    // 初始化图表
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chartContainer);
      this.chartInstance.setOption({
        title: { text: '测量数据趋势图' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['测量值1', '测量值2', '测量值3'] },
        xAxis: { type: 'category', data: this.chartData.xAxis },
        yAxis: { type: 'value', name: '测量值' },
        series: this.chartData.series.map(item => ({
          name: item.name,
          type: 'line',
          data: item.data,
          smooth: true
        }))
      });
    },

    // 更新图表
    updateChart() {
      this.chartInstance.setOption({
        xAxis: { data: this.chartData.xAxis },
        series: this.chartData.series.map((item, index) => ({
          data: item.data
        }))
      });
    },

    // 连接WebSocket服务器
    connectWebSocket() {
      this.wsError = '';
      // 构造WebSocket URL（ws://IP:端口）
      const wsUrl = `ws://${this.serverHost}:${this.serverPort}`;
      
      try {
        this.webSocket = new WebSocket(wsUrl);

        // 连接成功事件
        this.webSocket.onopen = () => {
          this.isConnected = true;
          this.isMeasuring = true;  // 连接成功后进入测量状态
          this.wsError = '';
        };

        // 接收数据事件（服务器主动推送测量数据）
        this.webSocket.onmessage = (event) => {
          const strData = event.data.toString().trim();
          // 验证数据格式（假设服务器返回"value1,value2,value3"）
          if (/^\d+\.?\d*(,\d+\.?\d*){2}$/.test(strData)) {
            this.currentData = strData;
          } else {
            this.wsError = `无效数据格式：${strData}`;
          }
        };

        // 错误事件
        this.webSocket.onerror = (error) => {
          this.wsError = `连接错误：${error.message}`;
          this.closeConnection();
        };

        // 关闭事件
        this.webSocket.onclose = () => {
          this.isConnected = false;
          this.isMeasuring = false;
          this.wsError = '连接已断开';
        };
      } catch (error) {
        this.wsError = `连接失败：${error.message}`;
      }
    },

    // 开始测量（触发WebSocket连接）
    startMeasurement() {
      if (!this.lotNumber || !this.smallLotNumber) {
        return alert('请先填写批次号和小lot数');
      }
      if (!this.serverHost || !this.serverPort) {
        return alert('请配置服务器IP和端口');
      }
      this.connectWebSocket();
    },

    // 断开连接
    closeConnection() {
      if (this.webSocket) {
        this.webSocket.close();  // 关闭WebSocket连接
        this.webSocket = null;
      }
      this.isConnected = false;
      this.isMeasuring = false;
    },

    // 保存数据
    saveData() {
      if (!this.currentData) return alert('请等待测量数据');
      const newItem = {
        lotNumber: this.lotNumber,
        smallLotNumber: this.smallLotNumber,
        testMethod: this.testMethod,
        inspector: this.inspector,
        value: this.currentData,
        time: new Date().toLocaleTimeString()
      };
      this.dataList.push(newItem);

      // 更新图表（保留最近20条）
      const timeLabel = new Date().toLocaleTimeString();
      this.chartData.xAxis = [...this.chartData.xAxis, timeLabel].slice(-20);
      const [v1, v2, v3] = this.currentData.split(',');
      
      this.chartData.series[0].data = [...this.chartData.series[0].data, Number(v1)].slice(-20);
      this.chartData.series[1].data = [...this.chartData.series[1].data, Number(v2)].slice(-20);
      this.chartData.series[2].data = [...this.chartData.series[2].data, Number(v3)].slice(-20);
      
      this.updateChart();
      // 自动滚动到表格底部
      this.$nextTick(() => {
        const tableWrapper = this.$el.querySelector('.table-wrapper');
        tableWrapper.scrollTop = tableWrapper.scrollHeight;
      });
    },

    // 清空数据
    clearData() {
      this.closeConnection();
      this.dataList = [];
      this.currentData = '';
      this.lotNumber = '';
      this.smallLotNumber = '';
      this.hasCPK = '';
      this.testMethod = 'X射线';
      this.inspector = this.inspectors[0];
      this.selectedIndex = -1;
      this.chartData = {
        xAxis: [],
        series: [
          { name: '测量值1', data: [] },
          { name: '测量值2', data: [] },
          { name: '测量值3', data: [] }
        ]
      };
      this.updateChart();
    },

    // 删除选中数据
    deleteSelected() {
      if (this.selectedIndex === -1) return alert('请选择要删除的数据');
      this.dataList.splice(this.selectedIndex, 1);
      this.selectedIndex = -1;
    }
  }
};
</script>

<style scoped>
/* 样式与之前相同，未做修改 */
.container {
  display: flex;
  height: 100vh;
  padding: 20px;
  gap: 20px;
}

.left-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 600px;
}

.left-top {
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-height: 300px;
}

.right-container {
  flex: 1;
  min-width: 600px;
}

.row {
  display: flex;
  gap: 10px;
  align-items: center;
}

.input-small {
  flex: 2;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.input-tiny {
  flex: 1;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.input-disabled {
  flex: 1;
  padding: 8px;
  background: #f5f5f5;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.btn:disabled {
  background: #c0d9f7;
  cursor: not-allowed;
}

.btn:hover:not(:disabled) {
  opacity: 0.9;
}

.select {
  padding: 8px;
  min-width: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
}

.select:disabled {
  background: #f5f5f5;
  color: #999;
}

.chart-container {
  flex: 1;
  height: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.table-wrapper {
  height: calc(100vh - 40px);
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e4e7ed;
}

th {
  background: #f8f9fa;
}

tr:hover {
  background: #f5f7fa;
}

tr.active {
  background: #e6f7ff;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin: 0 5px;
}

.status-indicator.connected {
  background: #52c41a;
  box-shadow: 0 0 4px #52c41a;
}

.status-indicator.disconnected {
  background: #ff4d4f;
  box-shadow: 0 0 4px #ff4d4f;
}

.error-msg {
  color: #ff4d4f;
  font-size: 12px;
  margin-left: 5px;
}
</style>
